package Thread;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TrainTicket {
    public static void main(String[] args) {
        ThreadPool();
    }
    public static void ThreadPool(){
        ExecutorService pool= Executors.newFixedThreadPool(10);

        Ticket3 ticket=new Ticket3();
        for(int i=0;i<4;i++){
            pool.execute(ticket);
        }
        pool.shutdown();
    }
}
class Ticket1 implements Runnable{
    int ticket=100;
    Lock lock=new ReentrantLock();
    @Override
    public void run() {
        while(true){
            try {
                lock.lock();
                if(ticket<=0){
                    return ;
                }
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println(Thread.currentThread()
                .getName()+" 正在售卖第"+ticket+"张票");
                ticket--;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
class Ticket2 implements Runnable{
    int ticket=100;
    Lock lock=new ReentrantLock();
    @Override
    public void run() {
        while(true){
            synchronized (this){
                try {
                    if(ticket<=0){
                        return ;
                    }
                    TimeUnit.MILLISECONDS.sleep(10);
                    System.out.println(Thread.currentThread()
                            .getName()+" 正在售卖第"+ticket+"张票");
                    ticket--;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class Ticket3 implements Runnable{
    int ticket=100;
    Lock lock=new ReentrantLock();
    @Override
    public void run() {
        while(true){
            if(sellTicket()){
                return ;
            }
        }
    }
    private synchronized boolean sellTicket(){
        try {
            if(ticket<=0){
                return true;
            }
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(Thread.currentThread()
                    .getName()+" 正在售卖第"+ticket+"张票");
            ticket--;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
}